package com.dh.blog.service.impl;

import java.util.List;
import java.util.Properties;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dh.blog.dao.BlogDao;
import com.dh.blog.dao.LeaveDao;
import com.dh.blog.dao.NewsDao;
import com.dh.blog.service.BlogService;
import com.dh.blog.vo.BlogVo;
import com.dh.blog.vo.CountVo;
import com.dh.blog.vo.LeaveVo;
import com.dh.blog.vo.NewsPagerVo;
import com.dh.blog.vo.PagerVo;
import com.ewei.web.common.exception.ErrorPageRuntimeException;

@Service("blogService")
@Transactional(readOnly=true)
public class BlogServiceImpl implements BlogService {
	private static final int DEFAULT_POOL_SIZE = 1;
	private static final int DEFAULT_LEAVE_WORD_SIZE = 5;
	@Resource
	private Properties config;
	@Resource
	private BlogDao blogDao; 
	@Resource
	private NewsDao newsDao;
	@Resource
	private LeaveDao leaveDao;
	@Transactional(readOnly=false)
	@Override
	public BlogVo doVisitBlog(String path) {
		BlogVo blog = blogDao.getBlogByPath(path);
		if(null != blog){
			int pondSize = DEFAULT_POOL_SIZE;
			String val = config.getProperty("max_pond_size");
			if(null != val && !"".equals(val)){
				pondSize = Integer.parseInt(val);
			}
			int pondId = (pondSize == 1)?
					1:(int) (Math.floor(Math.random()*pondSize+1));
			blogDao.count(blog.getId(), pondId);
		}else{
			//交由异常处理器处理
			throw new ErrorPageRuntimeException();
		}
		return blog;
	}
	@Override
	public CountVo getCounts(String blogId) {
		int crtTotal = blogDao.getPointsAll(blogId);
		int crtDay = blogDao.getPointsDay(blogId);
		CountVo countVo = new CountVo(); 
		countVo.setCrtDay(crtDay);
		countVo.setCrtTotal(crtTotal);
		return countVo;
	}
	@Override
	public BlogVo browse(String path) {
		BlogVo blog = blogDao.getBlogByPath(path);
		return blog;
	}
	@Override
	public PagerVo findNewsByPager(NewsPagerVo pager) {
		pager = newsDao.findPagerByBlog(pager);
		return pager;
	}
	@Override
	public List<LeaveVo> getTopLeaveWords(String blogId) {
		String param = config.getProperty("blog_leave_word_size");
		Integer num = null != param?Integer.valueOf(param)
				:DEFAULT_LEAVE_WORD_SIZE;
		return leaveDao.getTopByNum(blogId, num); 
	}
	@Override
	@Transactional(readOnly=false)
	public void doSaveleaveWord(LeaveVo leaveVo) {
		leaveDao.addOne(leaveVo);
	}
	@Override
	public BlogVo getBlogById(String id) {
		return blogDao.getBlogById(id);
	}
	@Override
	@Transactional(readOnly = false)
	public void flushCounter(String id) {
		Integer count = blogDao.getPointsDay(id);
		if(null !=count && count > 0){
			blogDao.initCounter(id);
			blogDao.flushCounter(id, count);
		}
	}
	@Override
	public List<BlogVo> getBlogList() {
		return blogDao.getBlogList();
	}

}
